#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# Author: Binux<i@binux.me>
#         http://binux.me
# Created on 2014-10-19 16:23:55

from __future__ import unicode_literals

from flask import render_template, request, json
from flask import Response
from .app import app
from pyspider.libs import result_dump


@app.route('/results')
def result():
    resultdb = app.config['resultdb']
    project = request.args.get('project')
    offset = int(request.args.get('offset', 0))
    limit = int(request.args.get('limit', 20))

    count = resultdb.count(project)
    results = list(resultdb.select(project, offset=offset, limit=limit))

    return render_template(
        "result.html", count=count, results=results,
        result_formater=result_dump.result_formater,
        project=project, offset=offset, limit=limit, json=json, result_strip=result_dump.strip
    )


@app.route('/search_result')
def search_result():
    resultdb = app.config['resultdb']
    project = request.args.get('project')
    offset = int(request.args.get('offset', 0))
    limit = int(request.args.get('limit', 20))
    search_text = request.args.get('search_text')
    count = resultdb.count_by_term(project, search_text)
    results = list(resultdb.select_by_term(project, search_text, offset=offset, limit=limit))

    return render_template(
        "search.html", count=count, results=results,
        result_formater=result_dump.result_formater,
        project=project, search_text=search_text, offset=offset, limit=limit, json=json
    )


@app.route('/results/dump/<project>.<_format>')
def dump_result(project, _format):
    resultdb = app.config['resultdb']
    # force update project list
    resultdb.get(project, 'any')
    if project not in resultdb.projects:
        return "no such project.", 404

    offset = int(request.args.get('offset', 0)) or None
    limit = int(request.args.get('limit', 0)) or None
    results = resultdb.select(project, offset=offset, limit=limit)

    if _format == 'json':
        valid = request.args.get('style', 'rows') == 'full'
        return Response(result_dump.dump_as_json(results, valid),
                        mimetype='application/json')
    elif _format == 'txt':
        return Response(result_dump.dump_as_txt(results),
                        mimetype='text/plain')
    elif _format == 'csv':
        return Response(result_dump.dump_as_csv(results),
                        mimetype='text/csv')


@app.route('/action_result', methods=['DELETE', ])
def deleteresult():
    rpc = app.config['scheduler_rpc']
    if rpc is None:
        return json.dumps({})
    taskdb = app.config['taskdb']
    resultdb = app.config['resultdb']

    project_taskid = request.form['project_taskid']
    project_name = project_taskid.split(":")[0]
    taskid = project_taskid.split(":")[1]

    result_info = resultdb.get(project_name, taskid)
    if not result_info:
        return "no such project.", 404
    task_info = taskdb.get_task(project_name, taskid)
    if not task_info:
        return "no such project.", 404
    try:
        resultdb.delete(project_name, taskid)
        taskdb.delete(project_name, taskid)
    except Exception as e:
        app.logger.warning('failed to remove project,taskid, %s, %s: %r', project_name, taskid, e)
        return 'failed to remove taskid', 400
    return json.dumps({"result": True}), 200, {'Content-Type': 'application/json'}


@app.route('/action_result_modify', methods=['PUT', ])
def modifyresult():
    rpc = app.config['scheduler_rpc']
    if rpc is None:
        return json.dumps({})
    taskdb = app.config['taskdb']
    resultdb = app.config['resultdb']

    project_taskid = request.form['project_taskid']
    project_name = project_taskid.split(":")[0]
    taskid = project_taskid.split(":")[1]
    result_info = resultdb.get(project_name, taskid)
    if not result_info:
        return "no such project.", 404
    result = result_info['result']

    task_info = taskdb.get_task(project_name, taskid)
    if not task_info:
        return "no such project.", 404

    for k, v in request.form.items():
        if k.startswith('result'):
            k = k[7:]
            v = '"' + v + '"'
            v = json.loads(v)
            result[k] = v

    try:
        resultdb.update(project_name, taskid, result)

    except Exception as e:
        app.logger.warning('failed to update project_taskid, %s_%s: %r', project_name, taskid, e)
        return 'failed to update taskid', 400
    return json.dumps({"result": True}), 200, {'Content-Type': 'application/json'}


@app.route('/action_search_result', methods=['DELETE', ])
def delete_search_result():
    rpc = app.config['scheduler_rpc']
    if rpc is None:
        return json.dumps({})
    taskdb = app.config['taskdb']
    resultdb = app.config['resultdb']

    all_project_taskid = request.form['all_project_taskid']
    project_taskid_group = all_project_taskid.split(',')

    for i in range(0, len(project_taskid_group)-1):
        project_name = project_taskid_group[i].split(":")[0]
        taskid = project_taskid_group[i].split(":")[1]

        result_info = resultdb.get(project_name, taskid)
        if not result_info:
            continue
        task_info = taskdb.get_task(project_name, taskid)
        if not task_info:
            continue
        try:
            resultdb.delete(project_name, taskid)
            taskdb.delete(project_name, taskid)
        except Exception as e:
            app.logger.warning('failed to remove project,taskid, %s, %s: %r', project_name, taskid, e)
            continue
    return json.dumps({"result": True}), 200, {'Content-Type': 'application/json'}